package top.wshape1.shiziapi.message.websocket;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import top.wshape1.shiziapi.common.constant.AuthConstant;
import top.wshape1.shiziapi.common.constant.RedisConstant;
import top.wshape1.shiziapi.common.domain.CommonUser;
import top.wshape1.shiziapi.common.utils.Base64Util;
import top.wshape1.shiziapi.message.constant.WebSocketConstant;

import java.util.Map;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-01-24
 */

@Component
@Slf4j
public class MyHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String userBase64 = request.getHeaders().getFirst(AuthConstant.HEADER_PAYLOAD_NAME);
        // 没有登录
        if (!StringUtils.hasLength(userBase64)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            log.info("WebSocket连接拒绝，原因：未登录，地址：{}", request.getRemoteAddress());
            return false;
        }

        CommonUser commonUser = Base64Util.decodeAndParse(userBase64, CommonUser.class);
        // 往session里存入userId
        attributes.put(WebSocketConstant.USER_ID, commonUser.getId());

        // 存在重复连接WebSocket
        if (Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(RedisConstant.USER_ONLINE_KEY, commonUser.getId()))) {
            // TODO 可能多端登录，可以将另一端下线
            return false;
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
    }
}
